'use strict';
var express = require('express');
var engine = require('ejs-mate'); //母版支持
var renderMiddleware = require('./middlewares/render'); //渲染中间件
var path = require('path');
var favicon = require('serve-favicon');
//var logger = require('morgan');
//var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routers = require('./router');
var config = require('./config');
require('./models/leancloudConnect.js')(config);//链接leancloud
var wxFilter = require('./middlewares/wxFilter.js');
var AV = require('leanengine');
var app = express();

var log4js = require('log4js');
//数据初始化
require('./initialize.js').init();
require('./initialize.js').activity();
require('./initialize.js').limitClassify();
require('./initialize.js').takeout();
log4js.configure(config.log4js);
var logger = log4js.getLogger('normal');
logger.setLevel('WARN');
app.use(log4js.connectLogger(logger, {level: 'auto', format:':method :url'}));

app.use(AV.Cloud.CookieSession({ secret: 'my secret', maxAge: 3600000, fetchUser: true }));

//微信登陆的拦截器
app.use(wxFilter);

// view engine setup
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 加入渲染中间件 实现每个页面渲染前自动载入loader
app.use(renderMiddleware.render);


// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, 'public')));

//添加微信的路由拦截
app.use('/wx',require('./wx'));

//添加一些脚本代码
app.use('/foo',require('./foo'));

app.use('/',routers);
//



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (config.dev == 'DEV') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

/**
 *
 */
module.exports = app;
